# -*-coding:Utf-8 -* 
""" Item loader module
"""
import bge, os, pickle
from ..gameplay import item as Item
from .parser import xakDocument

class ItemLoader(object):
	
	@classmethod
	def loadItem(cls, item):
		if not item in Item.MetaItem.ItemData:
			print(Item.MetaItem.ItemData)
			return
		item = ItemLoader(item,True)
		ItClass = item.load(True)
		if not item:
			return
		return ItClass._parseItem_(item)
		
	def __init__(self, path, forceCache = False):
		self.invalid = False
		name = os.path.splitext(os.path.basename(path))[0]
		cPath = bge.logic.expandPath('//config/item_cache/'+name)
		if os.path.lexists(cPath) and (forceCache or os.stat(path).st_mtime < os.stat(cPath).st_mtime):
			try:
				cFile = open(cPath,'rb')
			except OSError:
				os.remove(cPath)
			else:
				self.h = pickle.load(cFile)
				self.b = pickle.load(cFile)
				cFile.close()
				print("open")
				return
		if forceCache:
			self.invalid = True
			return
		item = xakDocument(path)
		item.build()
		if item.invalid:
			self.invalid = True
			item._clean()
			return
		h = item.getHead().childs.convertToDict()
		b = item.getBody().childs.convertToDict()
		item._clean()
		del item
		if not all(x in h for x in ('name','type','lib')):
			self.invalid = True
			return
		self.h = h
		self.b = b
		self.formatAll(name)
		print(h,b)
		try:
			cFile = open(cPath,'wb')
		except OSError:
			pass
		else:
			pickle.dump(h,cFile)
			pickle.dump(b,cFile)
			cFile.close()
			print('saved')
			
	def __bool__(self):
		return not(self.invalid)
	
	def formatTag(self, tag, forceTuple = False):
		tag = tag.copy()
		del tag[0]
		child = tag[1]
		del tag[1]
		text = child[0]
		del child[0]
		if len(child):
			for aTagName in child:
				child[aTagName] = [self.formatTag(x) for x in  child[aTagName]]
			if len(tag):
				child[0] = text
				text = child
			else:
				tag = child
		elif not len(tag) and not forceTuple:
			return text
		return (text,tag)
			
			 
	def formatAll(self,ItId):
		del self.h[0]
		for aKey in tuple(self.h.keys()):
			if len(self.h[aKey]) == 1 or aKey in ('name','type'):
				self.h[aKey] = self.formatTag(self.h[aKey][0])
			else:
				self.h[aKey] = [self.formatTag(x) for x in self.h[aKey]]
		self.h['id'] = ItId
		del self.b[0]
		for aKey in tuple(self.b.keys()):
			if len(self.b[aKey]) == 1:
				self.b[aKey] = self.formatTag(self.b[aKey][0], True)
			else:
				self.b[aKey] = [self.formatTag(x) for x in self.b[aKey]]
	
	@property
	def name(self):
		if self.invalid:
			return None
		return self.h['name']
				
	@property
	def type(self):
		if self.invalid:
			return None
		return self.h['type']
				
	@property
	def lib(self):
		if self.invalid:
			return None
		return self.h['lib']
		
	def load(self, returnClass = False):
		if self.type not in Item.MetaItem.ItemClass:
			print(self.type)
			print(Item.MetaItem.ItemClass)
			self.invalid = True
			return
		elif returnClass:
			return Item.MetaItem.ItemClass[self.type]
		elif not self.h['id'] in Item.MetaItem.ItemData:
			Item.MetaItem.ItemData.append(self.h['id'])
		
		
		
		
		
		
			
			
			
